<template>
  <el-form :model="form" label-width="auto" style="max-width: 600px">
    <el-form-item label="用户账号">
      <el-input v-model="form.name" />
    </el-form-item>
    <el-form-item label="用户密码">
      <el-input v-model="form.password" />
    </el-form-item>
    <el-form-item label="用户手机">
      <el-input v-model="form.tel" />
    </el-form-item>
    <el-form-item label="用户邮箱">
      <el-input v-model="form.email" />
    </el-form-item>
    <el-form-item label="用户性别">
      男<el-switch v-model="form.sex" style="margin-left: 5px;margin-right: 5px"/>女
    </el-form-item>
    <el-form-item label="用户生日">
      <el-col :span="11">
        <el-date-picker
            v-model="form.birthday"
            type="date"
            placeholder="请选择一个日期"
            style="width: 100%"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
        />
      </el-col>
    </el-form-item>
    <el-form-item label="用户等级">
      <el-input-number v-model="form.level" :step="1" :min="0" :max="100"/>
    </el-form-item>
    <el-form-item label="用户余额">
      <el-input-number v-model="form.money" :min="0" :max="1000" />
    </el-form-item>
    <el-form-item label="个人签名">
      <el-input v-model="form.sign_text" type="textarea" />
    </el-form-item>
    <el-form-item label="状态">
      <el-select v-model="form.status" placeholder="请选择用户状态">
        <el-option label="启用" value="online" />
        <el-option label="禁用" value="offline" />
        <el-option label="隐藏" value="hide" />
      </el-select>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="onSubmit">保存修改</el-button>
      <el-button @click="emit('close-dialog')">取消</el-button>
    </el-form-item>

  </el-form>
</template>

<script lang="ts" setup>
import {reactive, onMounted, watch} from 'vue'
import {ElLoading, ElMessage} from 'element-plus'
import {md5} from "js-md5";
import { defineProps } from 'vue';
import { defineEmits } from 'vue';
import router from "@/router";

const emit = defineEmits(['close-dialog'])

const props = defineProps({
  UID: String,
  cancel: Boolean,
});

const form = reactive({
  name: '',
  status: '',
  birthday: '',
  level: '',
  sign_text: '',
  money: 0,
  password:'',
  email:'',
  tel:'',
  sex: false,
})

const account_editUrl = 'https://movie.cpb2013.top/admin/account.php?mode=edit' // 替换为你的上传地址

const openFullScreen = () => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  return loading;
};

const closeFullScreen = (loading) => {
  loading.close();
};
// 表单提交处理函数
const onSubmit = async () => {
  console.log('提交表单:', form)
  let loading = openFullScreen();
  const formData = new FormData()

  // 遍历并添加到 FormData
  Object.keys(form).forEach((key) => {
    // 排除那些不是字符串或数字的键（例如布尔值或对象）
    // 因为 FormData 主要用于处理键值对形式的字符串数据
    if (typeof form[key] === 'string' || typeof form[key] === 'number') {
      formData.append(key, form[key]);
    } else if (typeof form[key] === 'boolean') {
      // 对于布尔值，你可以决定如何转换为字符串（例如，使用 'true' 或 'false'）
      formData.append(key, form[key] ? '女' : '男');
    }
  });

  formData.append('date', form.birthday); // 直接添加 form.type 的值
  formData.set('password',md5(form.password));
  formData.append('key', localStorage.getItem('key'));
  try {
    const response = await fetch(account_editUrl, {
      method: 'POST',
      headers: {
        // 'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
      },
      body: formData,
    })

    if (response.ok) {
      const result = await response.json()
      if(result['status'] ==='success')
      {
        ElMessage.success('修改成功！')
        emit('close-dialog')
        // this.$emit('close-dialog');
      }
      else if (result['status'] === 'danger') {
        localStorage.removeItem('key');
        ElMessage.error(result['msg']);
        await router.push('/login'); // Use router to navigate to the login page
      }
      else
      {
        ElMessage.error(result['msg'])
      }
    } else {
      ElMessage.error('添加失败！')
    }
  } catch (error) {
    ElMessage.error('请求失败！')
  }
  closeFullScreen(loading)
}

const fetchaccountData = async (UID) => {
  try {
    const formData = new FormData();
    formData.append('UID', UID); // 直接添加 form.type 的值
    formData.append('key', localStorage.getItem('key'));
    const response = await fetch('https://movie.cpb2013.top/admin/account.php?mode=show', {
      method: 'POST',
      headers: {
        // 'Authorization': `Bearer ${token}`,
        'Accept': 'application/json',
      },
      body: formData,
    });
    const responseData = await response.json();
    if (responseData.status === 'success') {
      const account = responseData.data.map((data: any) => ({
        UID: data.UID,
        email: data.email,
        birthday: data.birthday,
        sex: data.sex,
        name: data.name,
        status: data.status,
        tel: data.tel,
        sign_text: data.sign_text,
        last_login_time: data.last_login_time,
        last_logout_time: data.last_logout_time,
        rank: data.rank,
        vaild_time: data.vaild_time,
        last_edit_time: data.last_edit_time,
        level:data.level,
        money:data.money,
        online_status:data.online_status,
      }));

      if (account.length > 0) {
        Object.assign(form, account[0]);
      }

    } else if (responseData.status === 'danger') {
      localStorage.removeItem('key');
      ElMessage.error(responseData.msg);
      await router.push('/login'); // Use router to navigate to the login page
    }else {
      console.error('Error fetching movie data:', responseData.message);
    }
  } catch (error) {
    console.error('Error fetching movie data:', error);
  }
}

onMounted(() => {
  // const MID = '06a718d656fac9f771507e1872adc838'; // replace with actual MID
  fetchaccountData(props.UID);
});

watch(() => props.UID, (newUID) => {
  fetchaccountData(newUID);
});

</script>
